﻿using DeYi.NuGet.JsonReturn;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Ron.UploadFile.Common;

namespace WebApplication1.Controllers
{
    [ApiController]
    [Route("[controller]/[action]")]
    public class HomeController : ControllerBase
    {
        [HttpGet]
        public JsonReturn<dynamic> Index()
        {
            return new() { Status = ResultStatus.OK, Msg = "这是ok的吗？" };
        }

        public class UploadDto
        {
            public string org_name { get; set; }
            public IFormFile file
            {
                get; set;
            }
        }
        public class UploadManyDto
        {
            public string org_name { get; set; }
            public List<IFormFile> files
            {
                get; set;
            }
        }

        private async Task<string> SaveAs(IFormFile file, string destinationDir = null)
        {
            if (file == null)
                throw new ArgumentNullException("没有需要保存的文件");

            if (destinationDir != null)
                Directory.CreateDirectory(destinationDir);

            var newName = DateTime.Now.Ticks;
            var Extension = file.FileName.Substring(file.FileName.LastIndexOf('.'));
            var newFile = Path.Combine(destinationDir ?? "", $"{newName}{Extension}");
            using (FileStream fs = new FileStream(newFile, FileMode.CreateNew))
            {
                await file.CopyToAsync(fs);
                fs.Flush();
            }

            return newFile;
        }

        /// <summary>
        /// 单文件FormData提交
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonReturn<dynamic>> Upload([FromFile] UploadDto Input)
        {
            Console.WriteLine("这是单上传");
            if (Input == null)
                return new() { Status = ResultStatus.NotMeetRequirement, Msg = "不允许上传的文件类型" };

            string newFile = string.Empty;
            if (Input != null)
                newFile = await SaveAs(Input.file, AppDomain.CurrentDomain.BaseDirectory + "/files");

            return new() { Data = Input, Msg = "这是单上传：" + newFile };
        }


        /// <summary>
        /// 多文件FormData提交
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonReturn<dynamic>> UploadMany([FromFile] UploadManyDto Input)
        {
            Console.WriteLine("这是多文件上传");
            foreach (var item in Input.files)
            {
                await SaveAs(item, AppDomain.CurrentDomain.BaseDirectory + "/files");
            }
            return new() { Data = Input, Msg = "这是多文件上传" };
        }
    }
}
